package com.xxx.config.security.service;

import com.xxx.entity.Permission;
import com.xxx.entity.Role;
import com.xxx.entity.User;
import com.xxx.service.PermissionService;
import com.xxx.service.RoleService;
import com.xxx.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户认证处理类
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    @Resource
    private UserService userService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 调用根据用户查询用户信息的方法
        User user = userService.findUserByUsername(username);
        // 判断是否为空
        if(user==null){
            // 为空认证失败
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //查询用户的拥有的权限列表
        List<Permission> permissionList = permissionService.findPermissionListByUserId(user.getId());
        // 查询用户的角色
        List<String> roleName = roleService.findRoleNameByUserId(user.getId());
        //获取权限编码
        List<String> codeList = permissionList.stream()
                .filter(item -> item != null)
                .map(item -> item.getCode()).filter(item -> item != null)
                .collect(Collectors.toList());
        //转换成数组
        String[] strings = codeList.toArray(new String[codeList.size()]);

        //设置权限列表
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        user.setAuthorities(authorityList);
        //设置菜单列表
        user.setPermissionList(permissionList);
        user.setRoleNameList(roleName);
        // 查到用户
        return user;


    }
}
